---
title: ''
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
- \usepackage{caption}
- \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}


```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, readr, tidyr, argparse, stringr, here, glue, dplyr, knitr, kableExtra, forcats);

# Working directory and command line argument setup
task_output = "separated_outcomes_table"
current_script = paste0("generate_tables_and_figures/gen_", task_output, "/src/gen_", task_output, ".Rmd")
here::i_am(current_script)
source(here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "RESULTS",
  "OUTCOME_LABELS_FILE",
  "CONFIG_FILE",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()

```


```{r}

results <- read_csv(cl_args$RESULTS, show_col_types = F)

ylabels <- read_csv("../hand/baseline_outcome_labels.csv", show_col_types = F) %>%
  rename(outcome = value)

config <- read_yaml(cl_args$CONFIG_FILE)

source('../R/table_functions.R')
table_config <- read_yaml('../hand/tables_config.yaml')

```


```{r}

beta_se_digits <- table_config$digits$beta_se

# Filter to window and outcomes
outcomes_table <- results %>% 
  filter(window == config$window) %>%
  filter(outcome %in% config$outcomes) %>%
  mutate(outcome = fct_relevel(outcome, config$outcomes)) %>%
  arrange(outcome) %>%
  mutate(outcome_order = row_number()) %>%
  left_join(ylabels, by = "outcome") %>%
  mutate(across(.cols = where(is.numeric),
                .fns = ~ fmt(.x, decimals = beta_se_digits)))

# Stack standard errors under betas in parentheses
beta_se_stack <- stack_stderrs_under_betas(outcomes_table)

# Make table
table <- beta_se_stack %>%
  select(all_of(names(config$columns))) %>% 
  mutate(pval_itt = case_when(!is.na(pval_itt) ~ as.character(sprintf("%0.3f", as.numeric(pval_itt))), TRUE ~ pval_itt)) %>% 
  mutate(label = gsub("^Ever: ", '', label)) %>%
  mutate(label = ifelse(label=="Ever Shot", "Shooting Victimizations", label)) %>% 
  mutate(label = case_when(
    grepl("(Non-Shooting)", lag(label)) ~ "(Non-Shooting) Arrest",
    grepl("(Non-Shooting)", label) ~ substr(label, 1, nchar(label)-nchar("(Non-Shooting)")),
    TRUE ~ label)) %>% 
  mutate(label = case_when(label=="(Non-Shooting) Arrest" & lead(label)=="Robbery Arrests" ~ "(Non-Shooting) Arrests",
                           grepl("Non-fatal", label) ~ gsub("Non-fatal", "", label),
                           label=="Shooting Victimizations" & lead(label, 2)=="Homicide Arrest" ~ "Shooting Victimization",
                           TRUE ~ label)) %>% 
  kable(booktabs = table_config$booktabs, 
        longtable = table_config$longtable,
        col.names = unlist(config$columns),
        align = c(table_config$alignment$text, 
                  rep(table_config$alignment$numeric, 
                      length(config$columns) - 1)),
        linesep = "") %>% 
  kable_styling(font_size = 10.5) %>%
  group_rows("Counts", 1, 14) %>%
  group_rows("Indicators", 15, 28) %>%
  group_rows("\tShooting & Homicide Victimizations", 1, 4) %>%
  group_rows("\tShooting & Homicide Arrests", 5, 8) %>%
  group_rows("\tOther Serious Violent-Crime Arrests", 9, 14) %>%
  group_rows("\tShooting & Homicide Victimizations", 14+1, 14+4) %>%
  group_rows("\tShooting & Homicide Arrests", 14+5, 14+8) %>%
  group_rows("\tOther Serious Violent-Crime Arrests", 14+9, 14+14) %>%
  column_spec(1, width = config$col_width$text) %>%
  column_spec(2:length(config$columns), 
              width = config$col_width$numeric, latex_valign = 'm') %>% 
  add_indent(c(10, 24))

table

# SAVE

timestamp <- get_timestamp()

writeLines(table, glue(cl_args$OUT_DIR, "/outcomes_primary_separated_up_to_date.tex"))
writeLines(table, glue(cl_args$OUT_DIR, "/outcomes_primary_separated_{timestamp}.tex"))


```

